package com.hiray.demos.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.hiray.demos.R

class DrawableStateView : View {
    var isOk: Boolean = false

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)


    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        setOnClickListener {
            if (isOk)
                unOk()
            else setOk()
        }
    }

    override fun onCreateDrawableState(extraSpace: Int): IntArray {
        return if (isOk) {
            val drawableState = super.onCreateDrawableState(1)
            mergeDrawableStates(drawableState, intArrayOf(R.attr.state_ok))
            drawableState
        } else super.onCreateDrawableState(extraSpace)
    }

    private fun setOk() {
        isOk = true
        refreshDrawableState()
    }

    fun unOk() {
        isOk = false
        refreshDrawableState()

    }
}